package com.bjpowernode.mvc.controller;
import java.math.BigDecimal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.bjpowernode.common.enums.Code;
import com.bjpowernode.db.domain.User;
import com.bjpowernode.db.result.BidProductResult;
import com.bjpowernode.mvc.model.dto.bid.BidProductDTO;
import com.bjpowernode.mvc.model.dto.bid.BidRankDTO;
import com.bjpowernode.mvc.model.param.BidParam;
import com.bjpowernode.mvc.model.response.Response;
import com.bjpowernode.mvc.model.vo.bid.BidProductVO;
import com.bjpowernode.mvc.model.vo.bid.BidRankVO;
import com.bjpowernode.mvc.service.inter.BidService;
import com.bjpowernode.mvc.service.inter.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*@CrossOrigin*/
@RestController
public class BidController {

    @Resource
    private BidService bidService;
    @Resource
    private UserService userService;

    //显示排行榜
    @GetMapping(value = "/bid/rank")
    public Response showBidRank(){
        List<BidRankDTO> rankDTOList=bidService.queryBidRankFromRedis();
        return Response.ok(BeanUtil.copyToList(rankDTOList, BidRankVO.class));
    }



    @PostMapping(value = "/bid/product")
    public Response bidProduct(@RequestBody BidParam bidParam,
                               @RequestHeader("uid") Integer userId){

        Response response=Response.FAIL(Code.REQUEST_PARAM_ERR);
        if (bidParam.getBidMoney().doubleValue()%100==0) {

            //实名认证.
           User user= userService.queryById(userId);
           if (StrUtil.isBlank(user.getName())){
               return Response.FAIL(Code.REQUIRED_REALNAME);
           }


            //可以投资.
            BidProductDTO bidProductDTO=new BidProductDTO();
            bidProductDTO.setUserId(userId);
            bidProductDTO.setProductId(bidParam.getProductId());
            bidProductDTO.setBidMoney(bidParam.getBidMoney());

          String bidResult=  bidService.buyProduct(bidProductDTO);

          //根据枚举名称改为枚举对象.
            Code codeNum=Code.valueOf(bidResult);
            if (codeNum == Code.SUCC){
                //更新投资排行榜
                bidService.modifyBidRank(bidProductDTO.getUserId(),bidProductDTO.getBidMoney());

            }
            response=Response.BUILD(codeNum);

        }
        return response;

    }



    //分页查询用户的投资记录
    @GetMapping(value = "/bid/more")
    public Response queryBidByUid(@RequestHeader("uid") Integer userId,Integer pageNo,Integer pageSize){
        pageNo =(pageNo==null || pageNo<1 )?1:pageNo;
        pageSize=(pageSize == null || pageSize<1)?6:pageSize;

        //查询用户的投资金额记录.
       List<BidProductResult> bidList= bidService.queryRecentlyBidsByUserId(userId,pageNo,pageSize);

       //转换为vo
       List<BidProductVO> bidVoList= BeanUtil.copyToList(bidList, BidProductVO.class);
       //封装.
      return Response.ok(bidVoList );
    }

}
